function stringToHexArray(str) {
	let hexArray = [];
	for (let i = 0; i < str.length; i++) {
		// Convert each character to its hexadecimal representation
		let hex = str.charCodeAt(i).toString(16).toUpperCase().padStart(2, '0');
		// Add the hexadecimal representation to the array
		hexArray.push(hex);
	}
	return hexArray;
}


function getSuffix(hexData) {

	// 将十六进制数据转换为整数并进行无进位累加
	let sum = hexData.reduce((acc, hex) => acc + parseInt(hex, 16), 0);

	// 取低8位（即 sum 的值大于 0xFF 时，取低 8 位）
	sum = sum & 0xFF;

	return sum.toString(16).toUpperCase().padStart(2, '0')
}

function addValidateStr(data) {
	let arr = [];
	for (let i = 0; i < data.length; i++) {
		const hexData = stringToHexArray(data[i])
		const prefix = stringToHexArray(`A${i+1}`)
		const suffix = getSuffix(hexData)
		const fixed = ['3B', '0D', '0A']
		arr.push(prefix.concat(hexData).concat(suffix).concat(fixed).join(' '))
	}
	return arr;
}

function computeEncryptionData(deviceName = '', wifiName = '', wifiPassword = '') {
	const data = [
		'k18mjhsMHj5',
		`${deviceName}`,
		`${new Date().getTime().toString()}`,
		'a243dd86d12e8797827eccffb1ab086971916e8f58fb7ae1c71d4ec3453e3fe5',
		'06z00iqpcui7sc4',
		'LightSwitch',
		wifiName,
		wifiPassword,
	]
	return addValidateStr(data)
}


// function startConnect(data, resolve) {

// }

// 每 5 分钟内最多创建 20 个 TCPSocket
function connectingDevice(deviceName = '', wifiName = '', wifiPassword = '') {
	return new Promise((resolve, reject) => {
		try {
			let index = 0;
			let times = 8;
			const data = computeEncryptionData(deviceName, wifiName, wifiPassword);
			const tcp = wx.createTCPSocket(); // 创建 TCP 连接

			const startConnect = () => {
				tcp.write(data[index]);
			}

			const onConnect = (res) => {
				console.log('连接成功', res);
				startConnect();
			};

			const onMessage = (res) => {
				console.log('tcpResponse：', res);
				times--;
				if (res === 'success') {
					if (index >= data.length - 1) {
						cleanup();
						resolve();
					} else {
						index++;
						times = 8;
						startConnect();
					}
				} else {
					// 失败重试
					if (times > 0) {
						setTimeout(() => {
							startConnect();
						}, 800);
					} else {
						cleanup();
						reject(new Error('连接失败'));
					}
				}
			};

			const onError = (res) => {
				console.log('tcp连接出错', res);
				cleanup();
				reject(new Error('tcp连接出错: ' + res.errMsg));
			};

			const onClose = (res) => {
				console.log('tcp已关闭', res);
				cleanup();
			};

			const cleanup = () => {
				tcp.offConnect(onConnect);
				tcp.offMessage(onMessage);
				tcp.offError(onError);
				tcp.offClose(onClose);
			};

			tcp.onConnect(onConnect);
			tcp.onMessage(onMessage);
			tcp.onError(onError);
			tcp.onClose(onClose);

			tcp.connect({
				address: '192.168.4.1',
				port: 5050,
				timeout: 2,
			});
		} catch (e) {
			reject(e);
		}
	});
}


export {
	connectingDevice,
}